package com.mfcxy.admin.controller;

import java.io.File;
import java.io.IOException;
import java.net.PasswordAuthentication;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.mfcxy.entity.User;
import com.mfcxy.entityvo.SearchUser;
import com.mfcxy.entityvo.UserAddVo;
import com.mfcxy.exception.CustomException;
import com.mfcxy.service.IUserRoleService;
import com.mfcxy.service.IUserService;
import com.mfcxy.tools.BackJson;
import com.mfcxy.tools.CheckClassAttributes;
import com.mfcxy.tools.Tools;

/**
 * 管理员控制器
 * 
 * @author mfcxy
 *
 */
@Controller
@RequestMapping("/admin/user/")
public class UserController {

	@Autowired
	private IUserService userService;

	@Autowired
	private CheckClassAttributes checkObject;

	@Autowired
	private Tools tools;
	
	@Autowired
	private IUserRoleService userroleservice;

	/**
	 * 管理员列表页面
	 * 
	 * @ModelAttribute 会把提交的参数自动绑定到我们的 SearchUser 对象上
	 * @return
	 */
	@RequestMapping("list/{p}")
	public String list(Model model, @PathVariable(value = "p") int p, @ModelAttribute SearchUser searchuser) {

		Map<String, Object> map = null;

		int i = checkObject.check(searchuser);
		// 反射检查对象是否有查询的值
		if (i > 0) {
			map = userService.searchList(p, searchuser);
		} else {
			map = userService.selctList(p);
		}
		// 把数据存到model对象中，在jsp中可以直接取出来
		model.addAttribute("usermap", map);
		model.addAttribute("su", searchuser);
		// 返回视图
		return "admin/user_list";
	}

	/**
	 * 删除管理员
	 * 
	 * @param id
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "del", method = RequestMethod.POST)
	public BackJson deluser(@RequestParam("userId") int id) {
		BackJson bj = new BackJson();
		if (userService.delById(id) > 0) {
			bj.setCode(1);
		} else {
			bj.setCode(0);
			bj.setMsg("删除失败，请重试");
		}
		return bj;
	}

	// 批量删除管理员
	@ResponseBody
	@RequestMapping(value = "dels", method = RequestMethod.POST)
	public BackJson delusers(@RequestParam("ids") String ids) {
		BackJson bj = new BackJson();
		if (userService.delsByIds(ids) > 0) {
			bj.setCode(1);
		} else {
			bj.setCode(0);
			bj.setMsg("删除失败，请重试");
		}
		return bj;
	}

	/**
	 * 新增管理员视图
	 * 
	 * @return
	 */
	@RequestMapping("addview")
	public String addView() {
		return "admin/user_add";
	}

	/**
	 * 新增用户提交
	 *  jsr303 验证
	 * @param user
	 * @return
	 * @throws CustomException
	 */
	/*@RequestMapping(value = "add", method = RequestMethod.POST)
	public String add(@Valid @ModelAttribute UserAddVo user, BindingResult result) throws CustomException {
		//判断是否存在错误信息
		if (result.getErrorCount() > 0) {
			StringBuilder sb = new StringBuilder();
			for (FieldError error : result.getFieldErrors()) {
				// model.addAttribute(error.getField(), error.getDefaultMessage());
				// System.out.println(error.getField() + "=" + error.getDefaultMessage());
				sb.append(error.getDefaultMessage() + "<br/>");
			}
			throw new CustomException(sb.toString());
		}
		
		
		MultipartFile file = user.getImage();
		//文件上传
		user.setHead_portrait(tools.upload(file));
		userService.save(user);
		// redirect: 重定向的url
		return "redirect:/admin/user/details/" + user.getId();
	}*/

	/**
	 *  新增用户提交
	 *  自定义验证
	 * @param user
	 * @return
	 * @throws CustomException
	 */
	@RequestMapping(value = "add", method = RequestMethod.POST)
	public String add( @ModelAttribute UserAddVo user) throws CustomException {
			
		//数据效验
		user.checkAdd(userService);

		MultipartFile file = user.getImage();
		//文件上传
		user.setHead_portrait(tools.upload(file));
		userService.save(user);
		// redirect: 重定向的url
		return "redirect:/admin/user/details/" + user.getId();
	}

	/**
	 * 根据id查询用户
	 * 
	 * @param id
	 * @param model
	 * @return
	 */
	@RequestMapping("details/{id}")
	public String details(@PathVariable int id, Model model) {
		model.addAttribute("user", userService.findUserById(id));
		return "admin/user_details";
	}

	/**
	 * 检查用户名是否重复
	 * 
	 * @param username
	 * @return
	 */
	@ResponseBody
	@RequestMapping("checkusername")
	public BackJson checkUserName(@RequestParam("username") String username) {
		BackJson bj = new BackJson();
		// 如果是真就是存在用户名
		if (userService.checkUserName(username)) {
			bj.setCode(0);
			bj.setMsg("用户名已经存在");
		} else {
			bj.setCode(1);
		}
		return bj;
	}
	
	/**
	 *  更新管理视图
	 * @param id
	 * @param model
	 * @return
	 */
	@RequestMapping("updateview/{id}")
	public String updateview(@PathVariable int id , Model model) {
		model.addAttribute("user", userService.findUserById(id));
		return "admin/user_update";
	}
	
	/**
	 * 用户资料更新
	 * @param user
	 * @return
	 * @throws CustomException
	 */
	@RequestMapping(value = "update" , method = RequestMethod.POST)
	public String update(@ModelAttribute UserAddVo user) throws CustomException {
		//数据效验
		user.checkUpdate(userService);
		
		if(user.getImage().getSize() != 0) {
			MultipartFile file = user.getImage();
			//文件上传
			user.setHead_portrait(tools.upload(file));
		}
		userService.updateUserById(user);
		
		return "redirect:/admin/user/details/" + user.getId();
		
	}
	
	/**
	 * 重置密码视图
	 * @param id
	 * @param model
	 * @return
	 */
	@RequestMapping("restpwview/{id}")
	public String restPwView(@PathVariable int id , Model model) {
		model.addAttribute("user", userService.findUserById(id));
		return "admin/user_restpw";
	}
	
	/**
	 * 重置密码提交
	 * @param user
	 * @return
	 * @throws CustomException
	 */
	@RequestMapping(value = "restpw" , method = RequestMethod.POST)
	public String restPw(@ModelAttribute UserAddVo user) throws CustomException {
		user.checkRestPwd();
		userService.restpw(user.getPassword(), user.getId());
		return "redirect:/admin/user/details/" + user.getId();
	}

	/**
	 * 管理员列表页面(搜索)
	 * 
	 * @RequestParam 获取表单提交的参数 不推荐使用
	 * @return
	 * @throws InterruptedException
	 */
	/*
	 * @Deprecated
	 * 
	 * @RequestMapping("searchlist/{p}") public String searchList(Model model
	 * , @PathVariable(value="p") int p , @RequestParam(value = "username") String
	 * username , HttpServletRequest request) { Map<String, Object> map =
	 * userService.searchList(p, username); //把数据存到model对象中，在jsp中可以直接取出来
	 * model.addAttribute("usermap", map); model.addAttribute("username" ,
	 * username); //返回视图 return "admin/user_list"; }
	 */

	@ResponseBody
	@RequestMapping("listjson/{p}")
	public Map<String, Object> getlist(@PathVariable(value = "p") int p) throws InterruptedException {
		return userService.selctList(p);
	}
	
	
	/**
	 * 查询管理员的角色
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "selectrolelist")
	public BackJson selectRoleList(@RequestParam int uid) {
		Map<String, Object> map = new HashMap<>();
		map.put("list", userroleservice.selectURList(uid));
		BackJson bj = new BackJson();
		bj.setCode(1);
		bj.setData(map);
		return bj;
	}
	
	/**
	 * 修改管理员的角色
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "updaterole")
	public BackJson updateRole(@RequestParam String rids , @RequestParam int uid) {
		userroleservice.insertUR(rids, uid);
		BackJson bj = new BackJson();
		bj.setCode(1);
		return bj;
	}
	
}
